import {Button, Checkbox, Col, Form, Input, message, Modal, Row, Select, Space, Tag} from 'antd';
import React, { useEffect, useState } from 'react';
import { DragSortTable } from '@ant-design/pro-table';
import { ProColumns } from '@ant-design/pro-components';
import { detail, save,category } from '../../service';
import { DeleteOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons';
import FormItem from '../FormItem';
import dayjs from 'dayjs';
import MyUpload from "@/components/MyUpload";

type AddProps = {
  open: boolean;
  onClose: () => void;
  values?: Record<string, any>;
};

const Add: React.FC<AddProps> = ({ open, onClose, values }) => {
  const [form] = Form.useForm();
  const [dataSource, setDataSource] = useState<Record<string, any>[]>([]);
  const [formItemValue, setFormItemValue] = useState<Record<string, any>>({});
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);
  const [categories,setCategories] = useState<Record<string, any>[]>([]);
  const columns: ProColumns[] = [
    {
      title: '排序',
      dataIndex: 'sort',
      width: 60,
      className: 'drag-visible',
      render: (_, __, index) => <span>{index + 1}</span>,
    },
    {
      title: '名称',
      dataIndex: 'label',
    },
    {
      title: '类型',
      dataIndex: 'formType',
      width: 50,
      valueEnum: {
        text: {
          text: '文本',
        },
        number: {
          text: '数字',
        },
        select: {
          text: '多选',
        },
        radio: {
          text: '单选',
        },
      },
    },
    {
      title: '必填',
      dataIndex: 'isRequired',
      width: 50,
      valueEnum: {
        true: {
          text: '是',
        },
        false: {
          text: '否',
        },
      },
    },
    {
      title: '提示词',
      dataIndex: 'placeholder',
    },
    {
      title: '可选值',
      dataIndex: 'options',
      renderText: (text,record) => {
        if (record.type === 'select' || record.type == 'radio') {
          return (
            <span>{text.join(',')}</span>
          )
        }
        return <span>{text}</span>;
      },
    },
    {
      title: '操作',
      dataIndex: 'options',
      valueType: 'option',
      width: 60,
      renderText: (text, record) => [
        <Button
          type="text"
          icon={<EditOutlined style={{ color: '#1890ff' }} />}
          onClick={() => {
            setFormItemValue(record);
            handleModalOpen(true);
          }}
        />,
        <Button
          type="text"
          icon={<DeleteOutlined style={{ color: '#ff5500' }} />}
          onClick={() => {
            setDataSource(dataSource.filter((item) => item.key !== record.key));
          }}
        />,
      ],
    },
  ];
  useEffect(() => {
    category().then(result=>{
      setCategories(result.data || []);
    })



    if (values?.id) {
      detail({
        id: values?.id,
      }).then((result) => {
        setDataSource(result.data.formList || []);
        form.setFieldsValue(result.data);
      });
    }
  }, []);
  const handleDragSortEnd = (beforeIndex: number, afterIndex: number, newDataSource: any) => {
    console.log('排序后的数据', newDataSource);
    setDataSource(newDataSource);
    message.success('修改列表排序成功').then();
  };

  return (
    <Modal
      className='fullScreen'
      title={values?.id ? `修改：${values.name}` : '新增'}
      destroyOnClose
      onCancel={onClose}
      maskClosable={false}
      open={open}
      footer={null}
      width="100%"
      styles={{
        content: {
          height: '100%',
        }
      }}
    >

      <Form form={form} labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>
        <Row>
          <Col span={12}>
            <Form.Item name="id" label="id" style={{display:'none'}}>
              <Input />
            </Form.Item>
            <Form.Item name="name" label="应用名称" rules={[{ required: true, message: '必填' }]}>
              <Input />
            </Form.Item>
            <Form.Item name="memo" label="应用描述" rules={[{ required: true, message: '必填' }]}>
              <Input.TextArea autoSize={{ minRows: 4, maxRows: 4 }} />
            </Form.Item>
            <Form.Item label="应用图标" name='icon'>
              <MyUpload onSuccess={(url)=>form.setFieldValue("icon",url)} />
            </Form.Item>
            <Form.Item
              name="textAppCategoryId"
              label="应用分类"
              rules={[{ required: true, message: '必填' }]}
            >
             <Select allowClear style={{width:'100%'}}>
               {
                 categories.map(item=><Select.Option value={item.id}>{item.name}</Select.Option>)
               }
             </Select>
            </Form.Item>
            <Form.Item name="type" label="类别" rules={[{ required: true, message: '必填' }]}>
              <Select style={{ width: '100%' }}>
                <Select.Option value={0}>0</Select.Option>
                <Select.Option value={1}>1</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item
              name="isRecommend"
              label="是否推荐"
              valuePropName="checked"
            >
              <Checkbox />
            </Form.Item>
            <Form.Item name="prompt" label="提示词">
              <Input.TextArea autoSize={{ minRows: 8, maxRows: 8 }} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item noStyle>
              <Form.Item
                style={{ marginBottom: 0 }}
                name="userPrompt"
                label="自定义提示词"
                rules={[{ required: true, message: '必填' }]}
              >
                <Input.TextArea autoSize={{ minRows: 8, maxRows: 8 }} />
              </Form.Item>
              <Form.Item wrapperCol={{ offset: 4 }}>
                <div>
                  {dataSource.map((item) => (
                    <a
                      key={item.key}
                      style={{ marginRight: 16 }}
                      onClick={() => {
                        form.setFieldValue(
                          'userPrompt',
                          (form.getFieldValue('userPrompt')||'') + `{${item.label}}`,
                        );
                        form.validateFields(['userPrompt']).then();
                      }}
                    >
                      <Tag>{item.label}</Tag>
                    </a>
                  ))}
                </div>
              </Form.Item>
            </Form.Item>
            <Form.Item label="参数配置">
              <Button
                type="primary"
                icon={<PlusOutlined />}
                style={{ marginBottom: 8 }}
                onClick={() => {
                  handleModalOpen(true);
                  setFormItemValue({
                    key: `${dayjs().toDate().getTime()}`,
                  });
                }}
              >
                增加
              </Button>
              <DragSortTable
                scroll={{ y: 400 }}
                columns={columns}
                options={false}
                bordered
                size="small"
                rowKey="key"
                search={false}
                pagination={false}
                dataSource={dataSource}
                dragSortKey="sort"
                onDragSortEnd={handleDragSortEnd}
              />
            </Form.Item>
          </Col>
        </Row>
        <Form.Item wrapperCol={{ offset: 0 }}>
          <Button
            block
            type="primary"
            onClick={() => {
              console.log(form.getFieldsValue());
              if (dataSource.length <= 0) {
                message.error('请增加参数配置').then();
                return false;
              }
              // 检测自定义提示词是否全部包含参数配置
              let userPrompt = form.getFieldValue('userPrompt')||'';
              for (let i = 0; i < dataSource.length; i++) {
                if (userPrompt.indexOf('{' + dataSource[i].label + '}') < 0) {
                  message.warning('自定义提示词未包含：' + dataSource[i].label).then();
                  return false;
                }
              }
              form.validateFields().then((formValues) => {
                setLoading(true);
                save({
                  ...formValues,
                  formListStr: JSON.stringify(dataSource),
                }).then((result) => {
                  setLoading(false);
                  if (result.code == 0) {
                    message.success(result.msg).then();
                    onClose();
                  } else {
                    message.error(result.msg).then();
                  }
                });
              });
            }}
          >
            保存
          </Button>
        </Form.Item>
      </Form>
      {createModalOpen && Object.keys(formItemValue).length > 0 ? (
        <FormItem
          open={createModalOpen}
          onClose={() => {
            handleModalOpen(false);
            setFormItemValue({});
          }}
          onOk={(values) => {
            const newDataSource = [...dataSource];
            let current = newDataSource.filter((item) => item.key === values.key);
            if (current.length > 0) {
              setDataSource(
                newDataSource.map((item) => {
                  if (item.key == values.key) {
                    return values;
                  }
                  return item;
                }),
              );
            } else {
              newDataSource.push(values);
              setDataSource(newDataSource);
            }
            handleModalOpen(false);
          }}
          values={formItemValue}
        />
      ) : null}
    </Modal>
  );
};
export default Add;
